<template>
  <div class="app-container supplier-box">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :inline="true" label-width="90px" style="margin-bottom: 15px;">
          <el-form-item label="供应商名称">
            <el-input v-model="searchForm.name" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item label="业务联系人" label-width="90px">
            <el-input v-model="searchForm.wContacts" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item label="供应料品" label-width="80px">
            <el-select v-model="queryParams.sortId" class="select-box" ref="materials" placeholder="请选择"
              style="width: 100%;">
              <el-option v-for="item in optionsMaterials" :key="item.value" :label="item.sortName" :value="item.sortId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['po:supplier:query']" type="primary" icon="el-icon-search" @click="search">搜索
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['po:supplier:query']" plain icon="el-icon-menu" size="mini"
              @click="checkleAll">查询所有</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['po:supplier:add']" plain icon="el-icon-plus" size="mini"
              @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['po:supplier:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['po:supplier:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['po:supplier:print']" plain icon="el-icon-s-platform" size="mini"
              @click="handlePrint">打印</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['op:supplier:empty']" plain icon="el-icon-remove-outline" size="mini"
              @click="handleEmpty" :disabled="supplierData==0">清空</el-button>
          </el-col>
        </el-row>
        <!-- 供应商数据 -->
        <el-table :data="supplierData" border v-loading="loading" :height="maxHeight" :row-class-name="tableRowClassName">
          <el-table-column type="index" width="60" align="center" label="序号">
          </el-table-column>
          <el-table-column label="供应商名称" align="center" prop="name" width="230">
          </el-table-column>
          <el-table-column label="简称" align="center" prop="shortName" width="100">
          </el-table-column>
          <el-table-column label="公司地址" align="center" prop="addr" width="300">
          </el-table-column>
          <el-table-column label="电话" align="center" prop="tel">
          </el-table-column>
          <el-table-column label="业务联系人" align="center" prop="wContacts" />
          <el-table-column label="手机号" align="center" prop="wMobile" />
          <el-table-column label="供应料品" align="center" prop="sortName">
          </el-table-column>
          <el-table-column label="状态" align="center" key="status" width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding" width="200">
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button size="mini" type="text" class="basic-see" @click.stop="handleSee(scope.row)">查看
                </el-button>
                <el-button size="mini" class="basic-update" v-hasPermi="['po:supplier:edit']" type="text"
                  @click.stop="handleUpdate(scope.row)">修改
                </el-button>
                <el-button size="mini" v-hasPermi="['po:supplier:remove']" style="color: #f56c6c;" class="basic-delete"
                  type="text" @click.stop="handleDelete(scope.row)">删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 打印数据 -->
        <PrintPage :printData="printData" ref="startPrint" />
      </el-col>
    </el-row>
    <!-- 分页信息 -->
    <pagination v-show="total>=21" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getSupplierlList" />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog title="供应商" :visible.sync="open" width="600px" @close="close">
      <el-form ref="form" :model="supplierForm" label-width="95px" :rules="rules" :disabled="butChange=='seeStatus'">
        <el-row>
          <el-col :span="24">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="supplierForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="供应商别名">
              <el-input v-model="supplierForm.alias" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="简称">
              <el-input v-model="supplierForm.shortName" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属省/市">
              <el-cascader ref="classTree" :options="options" v-model="selectedOptions" @change="handleChangeCity"
                clearable>
              </el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="供应料品">
              <el-select v-model="selectMaterials" class="select-box" ref="materials" multiple placeholder="请选择"
                style="width: 100%;" @change="houseChange" clearable>
                <el-option v-for="item in optionsMaterials" :key="item.value" :label="item.sortName"
                  :value="item.sortId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商分类">
            <el-select v-model="selectType"  placeholder="请选择"
              @change="typeChange">
              <el-option v-for="item in optionsType" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商等级">
            <el-select v-model="selectTrust"  placeholder="请选择"
              @change="trustChange">
              <el-option v-for="item in optionsTrust" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公司地址">
              <el-input v-model="supplierForm.addr" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮编">
              <el-input v-model="supplierForm.postcode" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="电话">
              <el-input v-model="supplierForm.tel" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="supplierForm.remark" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="supplierForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="Billing-box">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="开票信息" name="first">
              <el-row style="height: 164px;">
                <el-col :span="24">
                  <el-form-item label="开户行">
                    <el-input v-model="supplierForm.bank" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="地址电话">
                    <el-input v-model="supplierForm.addr2" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="账号">
                    <el-input v-model="supplierForm.account" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="税号">
                    <el-input v-model="supplierForm.tax" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="业务联系人" name="second">
              <el-row style="height: 164px;">
                <el-col :span="12">
                  <el-form-item label="联系人" label-width="60px">
                    <el-input v-model="supplierForm.wContacts" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" label-width="60px">
                    <el-input v-model="supplierForm.wMobile" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="财务联系人" name="third">
              <el-row style="height: 164px;">
                <el-col :span="12">
                  <el-form-item label="联系人" label-width="60px">
                    <el-input v-model="supplierForm.fContacts" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" label-width="60px">
                    <el-input v-model="supplierForm.fMobile" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="butChange!=='seeStatus'">
        <el-button type="primary" v-if="butChange=='addStatus'" @click="submitForm('form')">确定</el-button>
        <el-button type="success" v-if="butChange=='updateStatus'" @click="submitForm('form')">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 供应商导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="form" label-width="70px" style="margin-bottom: 15px;" :rules="rules"
        :disabled="butChange=='seeStatus'">
        <el-form-item label="供应料品">
          <el-select v-model="selectMaterials" class="select-box" ref="materials" multiple placeholder="请选择"
            style="width: 100%;" @change="houseChange">
            <el-option v-for="item in optionsMaterials" :key="item.value" :label="item.sortName" :value="item.sortId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+'&sortId=' + upload.sortId + '&userOper=' + upload.userOper"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的供应商数据
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listSupplier,
    materialSort,
    addSupplier,
    updateSupplier,
    delSupplier,
    exportSupplier,
    dictMatching,
    emptyFile
  } from "../../api/supplier";
  import {
    isSerial
  } from "@/utils/cingsoft";
  import {
    provinceAndCityData
  } from 'element-china-area-data' //省市插件
  import PrintPage from "../../components/Supplier/print"; //打印组件
  import {
    getToken
  } from "@/utils/auth";
  //并行请求
  import axios from 'axios';
  import print from "print-js"; //打印js
  export default {
    name: "Posupplier",
    data() {
      //材料大类效验
      var checkSortId = (rule, value, callback) => {
        if (this.selectMaterials.length == 0) {
          return callback(new Error(''));
        } else {
          callback();
        }
      };

      return {
        // 遮罩层
        loading: true,
        // 供应商查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          name: "",
          sortId: ""
        },
        activeName: 'first',
        // 总条数
        total: 0,
        // 最大高度
        maxHeight: null,
        //供应商数据
        supplierData: [],
        //搜索参数
        searchForm: {
          name: "", //搜索供应商名称
          wContacts: "" //联系人
        },
        // 省市
        options: provinceAndCityData,
        selectedOptions: [],
        //供应商分类
        optionsType: [],
        selectType: "",
        //供应商信用
        optionsTrust: [],
        selectTrust: "",
        // 供应商导入参数
        upload: {
          // 是否显示弹出
          open: false,
          // 上传标题
          title: "",
          // 料品大类
          userOper: this.$store.getters.name,
          sortId: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/po/supplier/importData"
        },
        //打印数据
        printData: [],
        //打印状态
        printShow: false,
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        supplierForm: {
          name: "",
          shortName: "",
          status: "0",
          addr: "",
          sortId: "",
          tel: "",
          postcode: "",
          bank: "",
          addr2: "",
          account: "",
          tax: "",
          userOper: ""
        },
        // 材料大类
        optionsMaterials: [],
        selectMaterials: [],
        //弹框提交按钮状态，1（新增） 2（修改）
        butChange: "",
        // 表单校验
        rules: {
          name: [{
            required: true,
            trigger: 'blur'

          }],
        }
      }
    },
    created() {
      //初始化供应商列表
      this.getSupplierlList();
      //获取料品大类
      this.getMaterialSort();
      //获取字典
      this.getDict();
    },
    methods: {
      // 获取供应商数据
      getSupplierlList() {
        this.loading = true;
        listSupplier(this.queryParams).then(res => {
          if (res.code == 200) {
            this.loading = false;
            if (res.rows.length > 0) {
              let list = JSON.parse(JSON.stringify(res.rows));
              list.forEach((item, i) => {
               // let num = parseInt(i/5);
                if(i%5==0&&i!==0){
                  list[i-1].tag = 1
                }else{
                   list[i].tag = 0
                }
               this.supplierData = list;
              })

            } else {
              this.supplierData = [];
            }
            this.total = res.total;
            if (this.supplierData.length >= 21) { //条数总数大于显示出现滚动条
              this.maxHeight = (`${document.documentElement.clientHeight}` - 270);
            } else {
              this.maxHeight = ""
            }
          }
        })
      },
      // 间隔5行变色
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (row.tag == 1) {
          return 'warning-row';
        }
      },
      //清空
      handleEmpty(){
        this.$confirm('是否确认清空原料供应商?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return emptyFile();
        }).then(response => {
           this.getSupplierlList();
           this.msgSuccess("清空成功");
        })
      },
      // 料品大类
      getMaterialSort() {
        materialSort().then(res => {
          if (res.code == 200) {
            this.optionsMaterials = res.data;
          }
        })
      },

      /* 字典类型 */
      getDict(type) {
        return new Promise((resolve, reject) => {
          const _self = this;
          //并行请求
          axios.all([
            // 分类
            dictMatching({
              dictType: "po_supplier_type"
            }),
            // 信用等级
            dictMatching({
              dictType: "po_supplier_credit"
            }),

          ]).then(
            axios.spread(
              function(resType, resRrust) {
                if (resType.code == 200 && resRrust.code == 200) {
                  _self.optionsType = resType.rows;
                  _self.optionsTrust= resRrust.rows;
                  resolve()
                } else {
                  _self.msgError("获取信息失败")
                }
              }
            )
          )
        })
      },

      // 选择供应商分类
      typeChange(value){
        this.supplierForm.type = value;
      },

      // 选择供应商等级
      trustChange(value){
        this.supplierForm.trust = value;
      },

      //搜索
      search() {
        this.queryParams.wContacts = this.searchForm.wContacts;
        this.queryParams.name = this.searchForm.name;
        this.getSupplierlList();
      },

      // 查询所有
      checkleAll() {
        //清空搜索信息，避免干扰
        this.searchForm.name = "";
        this.queryParams.name = "";
        this.searchForm.wContacts = "";
        this.queryParams.wContacts = "";
        this.queryParams.sortId = "";
        this.getSupplierlList()
      },
      //供应商省市
      handleChangeCity(value) {
      },
      // 供应商tab签
      handleClick(tab, event) {
        console.log(tab, event);
      },
      // 供应商状态修改
      handleStatusChange(row) {
        this.supplierForm = Object.assign({}, row);
        let supplier = this.supplierForm;
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认' + text + '供应商?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateSupplier(supplier)
        }).then(() => {
          this.msgSuccess(text + "成功");
          this.reset();
          this.getSupplierlList();
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
          this.reset();
        });
      },

      // 新增供应商信息
      handleAdd() {
        this.reset();
        this.butChange = "addStatus";
        this.open = true;
      },
      // 查看供应商信息
      handleSee(row) {
        this.seeUpdate(row).then(() => {
          this.butChange = "seeStatus";
          this.open = true;
        })
      },

      // 修改供应商信息
      handleUpdate(row) {
        this.seeUpdate(row).then(() => {
          this.butChange = "updateStatus";
          this.supplierForm.version = row.version;
          this.open = true;
        })
      },

      // 导入按钮操作
      handleImport() {
        this.butChange = "uploadStatus";
        this.upload.sortId = "";
        this.selectMaterials = "";
        this.upload.title = "供应商信息导入";
        this.upload.open = true
      },


      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },

      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {
          dangerouslyUseHTMLString: true
        });
        this.getSupplierlList()
      },

      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },

      // 导出
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出供应商列表?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSupplier(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },

      // 打印
      handlePrint() {
        let number = 1;
        this.printData = this.supplierData;
        this.printData.forEach(obj => {
          obj.id = number++
        })
        setTimeout(() => {
          this.$print(this.$refs.startPrint.$refs.print);
        }, 0)
      },


      // 修改/查看/数据公共部分
      seeUpdate(row) {
        return new Promise((resolve, reject) => {
          if (row.sortId !== "") {
            // 字符串转整形
            let arr = row.sortId.split(",");
            let newArr = arr.map(v => {
              return v = parseInt(v)
            })
            this.selectMaterials = newArr; //料品大类
          } else {
            this.selectMaterials = "";
          }

          this.open = true;
          this.supplierForm = Object.assign({}, row); //拷贝物料信息
          if (this.supplierForm.city !== null && this.supplierForm.city !== undefined) {
            this.selectedOptions = this.supplierForm.city.split(",")
          } else {
            this.selectedOptions = [];
          }
          this.supplierForm.status = row.status;
          this.selectType = this.supplierForm.type;
          this.selectTrust = this.supplierForm.trust;
          resolve()
        })
      },

      // 选择料品大类
      houseChange(value) {
        if (this.butChange == "uploadStatus") {
          this.upload.sortId = value.join(",");
        } else {
          this.supplierForm.sortId = value.join(",");
          console.log(this.supplierForm.sortId)
        }

      },

      // 关闭selec下拉框
      closeSelect() {
        this.$refs.materials.blur();
      },

      // 提交新增供应商列表表单
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if (this.butChange == "addStatus") {
              this.supplierForm.userOper = this.$store.getters.name;
              if (this.selectedOptions.length > 0) {
                this.supplierForm.city = this.selectedOptions.join(",")
              } else {
                this.supplierForm.city = "";
              }
              addSupplier(this.supplierForm).then(res => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  this.getSupplierlList();
                  this.cancel()
                }
              }).catch(err => {
                this.msgError("新增失败");
              })
            } else {
              if (this.selectedOptions.length > 0) {
                this.supplierForm.city = this.selectedOptions.join(",")
              } else {
                this.supplierForm.city = "";
              }
              updateSupplier(this.supplierForm).then(res => { //触发保存提交
                if (res.code == 200) {
                  this.getSupplierlList();
                  this.msgSuccess("修改成功");
                  this.open = false;
                }
              }).catch(err => {
                this.msgError("修改失败");
              })

            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      //删除供应商
      handleDelete(row) {
        this.$confirm('确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return delSupplier(row.name);
        }).then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getSupplierlList();
            this.open = false;
          }
        })
      },

      /** 弹框取消 */
      cancel() {
        this.open = false;
        this.reset()
      },
      close() {
        this.reset()
      },

      /** 表单重置 */
      reset() {
        this.supplierForm = {
          name: "",
          shortName: "",
          status: "0",
          addr: "",
          sortId: "",
          tel: "",
          postcode: "",
          bank: "",
          addr2: "",
          account: "",
          tax: "",
          city: "",
          userOper: "",
          type :"",
          trust:""
        };
        this.selectMaterials = [];
        this.selectedOptions = [];
        this.selectType = "";
        this.selectTrust = "";
        this.activeName = 'first';
        this.resetSelector()
        this.resetForm("form");
      },
      //解决级联选择器回显高亮异常问题
      resetSelector() {
        if (this.$refs.classTree) {
          this.$refs.classTree.$refs.panel.activePath = [];
          this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
        }
      },
    },
    components: {
      PrintPage
    }

  };
</script>
<style lang="scss">
  .supplier-box {
    .el-tag.el-tag--info {
      color: #1890FF;
    }
    .el-table .warning-row {
      background-color: #F5F7FA;
    }
    .Billing-box {
      padding: 15px;
      box-shadow: 1px 1px 10px 1px #eee;
      border-radius: 5px;
      margin: 10px 10px 0px 10px;

      h2 {
        font-size: 15px;
        font-weight: 700;
        margin: 0;
        border-bottom: 1px solid #dfe6ec;
        padding-bottom: 15px;
        margin-bottom: 15px;
      }
    }

    .el-switch {
      display: flex;
      justify-content: center;
    }

    .el-radio__input.is-disabled.is-checked .el-radio__inner {
      background-color: #F5F7FA;
      border-color: #999;
    }

    .el-radio {
      margin-right: 18px;
    }

    .el-radio__label {
      padding-left: 5px;
    }

    .el-radio:nth-of-type(3) {
      margin-right: 0;
    }

    .el-switch.is-disabled {
      opacity: 1;
    }

    .el-table .el-table__header-wrapper th,
    .el-table .el-table__fixed-header-wrapper th {
      height: 35px;
    }

    .el-dialog__body {
      padding-right: 15px;
      padding-bottom: 20px;

    }

    .el-input.is-disabled .el-input__inner {
      color: #333;
    }

    .el-form-item--medium .el-form-item__content {
      margin-right: 10px !important;
    }
  }

  .close-select {
    overflow: hidden;

    i {
      float: right;
      margin-right: 15px;
      color: #909399;
      cursor: pointer;
    }
  }
</style>
